const { createClient } = require("redis");
const config = require("../../config");

class Registration {
    constructor() {
        if (config.redis.password){
            this.redisUrl = `redis://:${config.redis.password}@${config.redis.host}:${config.redis.port}/${config.redis.db}`;
        }else{
            this.redisUrl = `redis://${config.redis.host}:${config.redis.port}/${config.redis.db}`;
        }
    }

    async register(machineUuid, machineName, machineStatus = "idle") {
        const key = `registration:${machineUuid}`;
        const value = JSON.stringify({ machineUuid: machineUuid, machineName: machineName, machineStatus: machineStatus, lastUpdateTime: Date.now() });
        const redisClient = createClient({ url: this.redisUrl });
        await redisClient.connect();
        await redisClient.set(key, value);
        await redisClient.disconnect();
        return machineUuid;
    }

    async clean(isForced = false) {
        const redisClient = createClient({ url: this.redisUrl });
        await redisClient.connect();
        let keys = await redisClient.keys("registration:*");
        for (let key of keys) {
            let value = await redisClient.get(key);
            let clientInformation = JSON.parse(value);
            if (clientInformation) {
                let lastUpdateTime = clientInformation.lastUpdateTime;
                let now = Date.now();
                if (isForced || (!lastUpdateTime) || now - lastUpdateTime > 1 * 60 * 1000) {
                    await redisClient.del(key);
                }
            }
        }
        await redisClient.disconnect();
    }

    async getRemoteMachines() {
        const redisClient = createClient({ url: this.redisUrl });
        redisClient.connect();
        let keys = await redisClient.keys("registration:*");
        let remoteMachines = [];
        for (let key of keys) {
            let value = await redisClient.get(key);
            let remoteMachine = JSON.parse(value);
            remoteMachines.push(remoteMachine);
        }
        redisClient.disconnect();
        return remoteMachines;
    }

    async getRemoteMachine(uuid) {
        const redisClient = createClient({ url: this.redisUrl });
        redisClient.connect();
        let key = `registration:${uuid}`;
        let value = await redisClient.get(key);
        let remoteMachine = value && JSON.parse(value);
        return remoteMachine;
    }
}

module.exports = Registration;